package com.rdtravel.web;

import com.rdtravel.exceptions.CustomerAlreadyExitstException;
import com.rdtravel.services.CustomersService;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/customers")
class CustomersController {
	private static final String CREATE_VIEW = "customers/create";
	private final CustomersService customersService;

	@Autowired
	public CustomersController(CustomersService customersService) {
		this.customersService = customersService;
	}

	@RequestMapping(value = "create", method = RequestMethod.GET)
	public ModelAndView createForm(HttpSession session) {
		ModelAndView modelAndView = new ModelAndView(CREATE_VIEW);
		modelAndView.addObject(new CustomerCreateForm());
		return modelAndView;
	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView create(@Valid CustomerCreateForm customerCreateForm,
			BindingResult bindingResult, HttpSession session) {
		if (!bindingResult.hasErrors()) {
			try {
				customersService.create(customerCreateForm.toCustomer());
				SecurityContextHolder.getContext().setAuthentication(	
						new UsernamePasswordAuthenticationToken(
								customerCreateForm.getUsername(),
								customerCreateForm.getPassword())); 
			} catch (CustomerAlreadyExitstException ex) {
				bindingResult.rejectValue("username", "customerAlreadyExists");
			}
		}
		if (bindingResult.hasErrors()) {

			return new ModelAndView(CREATE_VIEW);
		}
		String urlAfterAuthentication=(String) session.getAttribute(LoginController.URL_AFTER_AUTHENTICATION);
		if (urlAfterAuthentication == null) {
			return new ModelAndView("redirect:/");
		} else {
			return new ModelAndView("redirect:"+urlAfterAuthentication);
		}
	}
}
